<template>
  <div v-loading="loading"  class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">商品名称</label>
        <el-input v-model="query.goodsName" clearable placeholder="商品名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="form.goodsName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="商品类型" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio label="1">小区商品</el-radio>
              <el-radio label="2">社区商品</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" :max="999" style="width: 150px;" />
          </el-form-item>
          <el-form-item label="规格 " prop="specs">
            <el-input v-model="form.specs" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="产地" prop="origin">
            <el-input v-model="form.origin" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="保质期" prop="expiration">
            <el-input v-model="form.expiration" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="描述" prop="describe">
            <el-input v-model="form.describe" :rows="3" type="textarea" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="商品数量" prop="goodsNumber">
            <el-input-number v-model="form.goodsNumber" :min="0" :max="999" style="width: 150px;" />
          </el-form-item>
          <el-form-item label="商品图片" prop="path">
            <!-- 文件上传组件 -->
            <el-upload
              class="upload-demo"
              :limit="10"
              :action="fileUploadApi"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="removePic"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :on-error="handleError"
              :file-list="fileList"
              list-type="picture-card"
            >
              <i class="el-icon-plus" />
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="goodsName" label="商品名称" />
        <el-table-column prop="type" label="商品类型" >
          <template slot-scope="scope">
            <!-- 根据不同的值显示不同的内容 -->
            <span v-if="scope.row.type == 1">小区商品</span>
            <span v-else-if="scope.row.type == 2">社区商品</span>
            <span v-else />
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="销量" />
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="specs" label="规格 " />
        <el-table-column prop="origin" label="产地" />
        <el-table-column prop="expiration" label="保质期" />
        <el-table-column prop="describe" label="描述" />
        <el-table-column prop="goodsNumber" label="商品数量" />
        <el-table-column prop="createTime" label="创建日期" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column v-if="checkPer(['admin','goodsManage:edit','goodsManage:del'])" label="操作" width="300px" align="center">
          <template slot-scope="scope">
            <div class="grid-content bg-purple-light">
              <udOperation
                :data="scope.row"
                :permission="permission"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <el-dialog :visible.sync="dialogPictrueVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </div>
</template>

<script>
import crudGoodsManage from '@/api/system/goodsManage'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

const defaultForm = { id: null, createTime: null, updateTime: null, createBy: null, updateBy: null, deleted: null, goodsName: null, type: null, sales: null, price: null, specs: null, origin: null, expiration: null, describe: null, xqId: null, goodsNumber: null, shelves: null }
export default {
  name: 'GoodsManageAgents',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '商品管理', url: 'api/goodsManage', idField: 'id', sort: 'id,desc', crudMethod: { ...crudGoodsManage }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'goodsManage:add'],
        edit: ['admin', 'goodsManage:edit'],
        del: ['admin', 'goodsManage:del']
      },
      rules: {
        goodsName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' }
        ],
        specs: [
          { required: true, message: '规格 不能为空', trigger: 'blur' }
        ],
        origin: [
          { required: true, message: '产地不能为空', trigger: 'blur' }
        ],
        expiration: [
          { required: true, message: '保质期不能为空', trigger: 'blur' }
        ],
        describe: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ],
        goodsNumber: [
          { required: true, message: '商品数量不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'goodsName', display_name: '商品名称' }
      ],
      headers: { 'Authorization': getToken() },
      fileList: [],
      goodsPhotos: [],
      loading: false,
      dialogImageUrl: '',
      dialogPictrueVisible: false
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.optShow.download = false
      return true
    },
    // 编辑之前
    [CRUD.HOOK.beforeToEdit](obj, row) {
      this.loading = true
      crudGoodsManage.detail(row.id).then(data => {
        if (data && data.data && data.data.detail) {
          const goodsPhoto = data.data.detail
          const resPhotos = []
          for (const item of goodsPhoto) {
            resPhotos.push({ 'storageId': item.storageId, 'path': item.path })
            this.fileList.push({ response: { id: item.storageId }, url: item.path })
          }
          this.goodsPhotos = resPhotos
        }
        this.loading = false
      })
      return true
    },
    // 取消添加之前
    [CRUD.HOOK.beforeAddCancel]() {
      this.fileList = []
      this.goodsPhotos = []
      return true
    },
    // 取消编辑之前
    [CRUD.HOOK.beforeEditCancel]() {
      this.fileList = []
      this.goodsPhotos = []
      return true
    },
    // 提交之前
    [CRUD.HOOK.beforeSubmit]() {
      if (!this.goodsPhotos || this.goodsPhotos.length === 0) {
        this.$message.error('请上传文件')
        return false
      }
      this.crud.form.detail = this.goodsPhotos
      return true
    },
    // 提交保存之后
    [CRUD.HOOK.afterSubmit]() {
      this.fileList = []
      this.goodsPhotos = []
      return true
    },
    // 上下架
    conversionShelves(id, shelves) {
      this.loading = true
      crudGoodsManage.shelves(id, shelves).then(data => {
        this.loading = false
        this.crud.operationSuccessNotify()
        this.crud.refresh()
      })
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogPictrueVisible = true
    },
    // 删除图片
    removePic(file) {
      const beforRemove = this.goodsPhotos
      const afterRemove = []
      for (var i = 0; i < beforRemove.length; i++) {
        if (beforRemove[i].storageId !== file.response.id) {
          afterRemove.push(beforRemove[i])
        }
      }
      this.goodsPhotos = afterRemove
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 5mb!')
      }
      return isLt2M
    },
    handleSuccess(res, file, fileList) {
      this.goodsPhotos.push({ 'storageId': res.id, 'path': res.path })
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.dialogVisible = false
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    }
  }
}
</script>

<style scoped>

</style>
